<template>
  <Header title="修改密码" />
  <div class="my_content">
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      class="demo-ruleForm"
      label-width="60px"
      label-position="top"
    >
      <el-form-item prop="user" label="用户：">
        <div class="userName">{{ user.username }}</div>
      </el-form-item>
      <el-form-item prop="oldPassword" label="旧密码：">
        <el-input
          v-model.trim="ruleForm.oldPassword"
          type="text"
          autocomplete="off"
          placeholder="请输入旧密码"
          size="large"
        />
      </el-form-item>
      <el-form-item prop="password" label="新密码：">
        <el-input
          v-model.trim="ruleForm.password"
          type="password"
          autocomplete="off"
          placeholder="请输入密码"
          maxlength="12"
          size="large"
        />
      </el-form-item>
      <el-form-item prop="passwordAgain" label="再次输入新密码：">
        <el-input
          v-model.trim="ruleForm.passwordAgain"
          type="password"
          autocomplete="off"
          placeholder="请输入邮箱地址"
          maxlength="32"
          size="large"
        />
      </el-form-item>
    </el-form>
  </div>
  <el-button
    class="footerBtn"
    type="primary"
    @click="submitForm(ruleFormRef)"
    :loading="loginLoading"
    size="large"
    >确认修改</el-button
  >
</template>

<script lang="ts" setup>
import Header from "@/components/Header.vue"
import { reactive, ref } from "vue"
import { ElMessage } from "element-plus"
import type { FormInstance } from "element-plus"
import { appReset } from "@/api/index"
import { getSession } from "@/util/tools"
import { useRouter } from "vue-router"

const $router = useRouter()

const loginLoading = ref(false)

const ruleFormRef = ref<FormInstance>()

onMounted(() => {
  const userInfo = getSession("userInfo")
  if (userInfo) {
    user.userId = userInfo.userId
    user.username = userInfo.username
  }
})

const validateUserName = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("请输入旧密码!"))
  } else {
    callback()
  }
}
const validatePassword = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("请输入新密码"))
  } else if (value.length < 6) {
    callback(new Error("请输入6至12位的新密码"))
  } else if (!/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,12}$/.test(value)) {
    callback(new Error("请输入6至12位包含数字、字母（大小写）密码"))
  } else {
    callback()
  }
}
const validatePasswordAgain = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("请输入电子邮箱地址!"))
  } else if (ruleForm.passwordAgain !== ruleForm.password) {
    callback(new Error("两次密码输入不一致!"))
  } else {
    callback()
  }
}

const user = reactive({
  userId: "",
  username: ""
})

const ruleForm = reactive({
  oldPassword: "",
  password: "",
  passwordAgain: ""
})

const rules = reactive({
  oldPassword: [{ validator: validateUserName, trigger: "blur" }],
  password: [{ validator: validatePassword, trigger: "blur" }],
  passwordAgain: [{ validator: validatePasswordAgain, trigger: "blur" }]
})

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      const res = await appReset({
        userId: user.userId,
        newPassword: ruleForm.password,
        password: ruleForm.oldPassword
      })
      if (res.code === 200) {
        ElMessage.success("修改密码成功！")
        loginOut()
      } else {
        ElMessage.error(res.msg)
      }
    } else {
      return false
    }
  })
}
const loginOut = () => {
  sessionStorage.clear()
  $router.push({ path: "/login" })
}
</script>
<style scoped lang="less">
@import "../styles/common.less";

:deep(.el-form-item__content) {
  margin-bottom: 30px;
}

.userName {
  width: 100%;
  height: 42px;
  padding: 0 10px;
  border: 1px solid #909399;
  border-radius: 4px;
  line-height: 42px;
}
</style>
